package com.suning.sawp.web.controller.in;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.suning.sawp.constants.ConfigConstants;
import com.suning.sawp.constants.ErrorCodeConstants;
import com.suning.sawp.constants.LoggerConstants;
import com.suning.sawp.dto.common.QueryResult;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.dto.precharge.ChargeOrderForPageRtn;
import com.suning.sawp.dto.precharge.CommonRtn;
import com.suning.sawp.intf.precharge.PreChargeService;
import com.suning.sawp.service.util.ConfigUtil;
import com.suning.sawp.service.util.DateUtils;
import com.suning.sawp.web.controller.DjBaseController;
import com.suning.sawp.web.exception.MyGsonView;

@Controller
@RequestMapping("/precharge")
public class PreChargeInController extends DjBaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoggerConstants.SAWP_SERVICE);

    @Autowired
    PreChargeService preChargeService;

    /**
     * 
     * 功能描述: 是否超过最大导出数量<br>
     * 〈功能详细描述〉
     * 
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/checkExportCount.do")
    public MyGsonView isExportBeyond(String startTime, String endTime) {
        MyGsonView gsonView = createGsonView();
        ReturnMsg<CommonRtn> ret = new ReturnMsg<CommonRtn>();
        CommonRtn data = new CommonRtn();
        if (StringUtils.isBlank(startTime) || StringUtils.isBlank(endTime)) {
            ret.setRetFlag(ReturnMsg.FAIL);
            ret.setErrorCode(ErrorCodeConstants.ERR_0001);
            ret.setErrorMessage(ErrorCodeConstants.ERR_MAP.get(ErrorCodeConstants.ERR_0001));
            return gsonView;
        }
        try {
            Integer count = preChargeService.queryExportCount(startTime, endTime);
            String maxCount = ConfigUtil.getConfig(ConfigConstants.SAWP_CONFIG_PATH, ConfigConstants.MAX_EXPORT_COUNT,
                    ConfigConstants.DEFAULT_MAX_EXPORT_COUNT);
            if (count != null && count <= Integer.parseInt(maxCount)) {
                ret.setRetFlag(ReturnMsg.SUCCESS);
                data.setSysMsg(count.toString());
                ret.setData(data);
            } else if (count != null) {
                ret.setError(ErrorCodeConstants.ERR_0006, maxCount);
            }
        } catch (Exception e) {
            LOGGER.error("isExportBeyond ERROR", e);
            ret.setRetFlag(ReturnMsg.FAIL);
            ret.setErrorCode(ErrorCodeConstants.ERR_0002);
            ret.setErrorMessage(ErrorCodeConstants.ERR_MAP.get(ErrorCodeConstants.ERR_0002));
        }
        gsonView.addStaticAttribute("ret", ret);
        gsonView.setJsonObjectName("ret");
        return gsonView;
    }

    @RequestMapping("/exportRecordExcel.do")
    public void exportOrderRecord(String startTime, String endTime, HttpServletResponse response) {
        InputStream is = null;
        OutputStream os = null;
        File file = null;
        try {
            file = preChargeService.exportRecordExcel(startTime, endTime);
            is = new FileInputStream(file);
            os = response.getOutputStream();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-download");
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
            String time = formatter.format(new Date());
            String fileName = "chargeRecord_" + time + ".xlsx";
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            byte[] buffer = new byte[4096];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            os.flush();
        } catch (Exception e) {
            LOGGER.error("批量导出出现错误", e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    LOGGER.error("关闭os流失败", e);
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    LOGGER.error("关闭is流失败", e);
                }
            }
            if (file != null) {
                try {
                    file.delete();
                } catch (Exception e) {
                    LOGGER.error("删除file：" + file.getAbsolutePath() + "失败", e);
                }
            }
        }
    }

    /**
     * 
     * 功能描述: 查询现金充值记录分页<br>
     * 〈功能详细描述〉
     * 
     * @param startTime
     * @param endTime
     * @param regionCode
     * @param storeCode
     * @param pageNo
     * @param pageSize
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryOrder.do")
    public MyGsonView queryOrder(String startTime, String endTime, String regionCode, String storeCode, int pageNo,
            int pageSize) {
        Object[] args = { startTime, endTime, regionCode, storeCode, pageNo, pageSize };
        LOGGER.debug(
                "PreChargeInController.queryOrder, startTime:{}, endTime:{}, regionCode:{}, storeCode:{}, pageNo:{}, pageSize:{}",
                args);
        ReturnMsg<QueryResult<ChargeOrderForPageRtn>> rtn = new ReturnMsg<QueryResult<ChargeOrderForPageRtn>>();
        if (StringUtils.isBlank(startTime) || StringUtils.isBlank(endTime) || StringUtils.isBlank(regionCode)) {
            rtn.setError(ErrorCodeConstants.ERR_0001);
            return setGsonView(rtn);
        }
        int size = pageSize;
        int no = pageNo;
        // 设置默认的页面大小和起始位置10,0
        if (size < 1) {
            size = 10;
        }
        if (no < 1) {
            no = 1;
        }

        try {
            int startIndex = (no - 1) * size;
            rtn = preChargeService.queryOrderForPage(startTime, endTime, regionCode, storeCode, startIndex, size, null);
        } catch (Exception e) {
            rtn.setError(ErrorCodeConstants.ERR_0002);
            LOGGER.error("查询现金充值记录统计异常", e);
        }

        return setGsonView(rtn);
    }

    /**
     * 
     * 功能描述: 导出已经验过券的excel<br>
     * 〈功能详细描述〉
     *
     * @param startTime
     * @param endTime
     * @param response
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/exportPrechargeStat.do")
    public void exportPrechargeStat(String activityName, String startTime, String endTime, String storeCode,
            String regionCode, HttpServletResponse response) {
        OutputStream ouputStream = null;
        try {
            if (StringUtils.isBlank(startTime) || StringUtils.isBlank(endTime) || StringUtils.isBlank(regionCode)) {
                response.setContentType("text/html; charset=UTF-8");
                response.setHeader("Cache-Control", "no-cache");
                ouputStream = response.getOutputStream();
                ouputStream.write(ErrorCodeConstants.ERR_MAP.get(ErrorCodeConstants.ERR_0001).getBytes("UTF-8"));
            } else {
                Workbook workbook = preChargeService.exportPrechargeStat(activityName, startTime, endTime, regionCode,
                        storeCode);
                response.setContentType("application/x-download");
                String time = DateUtils.getNowFullStr();
                response.setHeader("Content-disposition", "attachment;filename=preCharge_" + time + ".xlsx");
                ouputStream = response.getOutputStream();
                workbook.write(ouputStream);
            }
            ouputStream.flush();
            ouputStream.close();
        } catch (IOException e) {
            LOGGER.error("exportValidHorizCoupon 导出excel出错", e);
        }
    }

    /**
     * 
     * 功能描述: 检查已验券的记录数是否已经超过约定值<br>
     * 〈功能详细描述〉
     *
     * @param startTime
     * @param endTime
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/checkPrechargeStatExport.do")
    public MyGsonView checkPrechargeStatExport(String activityName, String startTime, String endTime, String storeCode,
            String regionCode) {
        ReturnMsg<String> ret = preChargeService.checkPrechargeStatExport(activityName, startTime, endTime, regionCode,
                storeCode);
        return setGsonView(ret);
    }
}
